import { useEffect, useState } from 'react'

// TS 类型
type UseCountDown = () => [number | null, boolean, (seconds?: number) => void]
export const useCountDown: UseCountDown = () => {
  const [count, setCount] = useState<number | null>(null)
  const [disabled, setDisabled] = useState(false)
  const startCount = (seconds = 10) => {
    seconds = Math.round(Math.abs(seconds || 10))
    setDisabled(true)
    setCount(seconds)
  }
  useEffect(() => {
    if (count == null) return setDisabled(false)
    const timer = setTimeout(() => {
      if (count == 0) {
        setCount(null)
      } else {
        setCount((pre) => pre! - 1)
      }
    }, 1000)
    return () => clearTimeout(timer)
  }, [count])
  return [count, disabled, startCount]
}
